package servlets;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import managers.UserManager;

import security.Encryption;

import entities.User;

/**
 * Servlet implementation class AccountServlet
 */
@WebServlet("/Account")
public class AccountServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	@EJB
	UserManager userManager;
	
    public AccountServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		User u = (User) request.getSession().getAttribute("user");
		System.out.println(u + "USER");
		request.getSession().setAttribute("user", u);
		request.getRequestDispatcher("/WEB-INF/AccountManage.jsp").forward(request, response);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//should only update
		User u = (User) request.getSession().getAttribute("user");
		System.out.println(u);
		
		String username = request.getParameter("username");
		
		String email = request.getParameter("email");
		String emailConfirm = request.getParameter("emailconfirm");
		
		String password = request.getParameter("password");
		String passwordConfirm = request.getParameter("passwordconfirm");
		
		String fname = request.getParameter("fname");
		
		String lname = request.getParameter("lname");
		
		if(fname != null){
			u.setFname(fname);
		}
		if(lname != null){
			u.setLname(lname);
		}
		if(email != null && emailConfirm != null){
			boolean taken = false;
			for(User temp : userManager.getUsers()){
				if(email.equals(emailConfirm)){
					if(email.equals(temp.getEmail())){
						taken = true;
					}
				}
			}
			if(!taken)
				u.setEmail(email);
		}
		if(password != null && passwordConfirm != null){
			if(Encryption.digest(password).equals(Encryption.digest(passwordConfirm))){
				u.setPassword(Encryption.digest(password));
			}
		}
		if(username != null){
			boolean taken = false;
			for(User temp : userManager.getUsers()){
				if(username.equals(temp.getUsername())){
					taken = true;
				}
			}
			if(!taken)
				u.setUsername(username);					
		}
		
		userManager.update(u);
		
		
		request.getSession().setAttribute("user", u);
		request.getRequestDispatcher("/WEB-INF/AccountManage.jsp").forward(request, response);
	}

}
